package com.rickpan.dto.response;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rickpan.entity.Team;
import io.swagger.v3.oas.annotations.media.Schema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 团队设置响应DTO
 */
@Schema(description = "团队设置响应")
public class TeamSettingsResponse {

    private static final Logger logger = LoggerFactory.getLogger(TeamSettingsResponse.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Schema(description = "团队ID", example = "1")
    private Long teamId;

    @Schema(description = "团队可见性", example = "INTERNAL")
    private Team.Visibility visibility;

    @Schema(description = "加入方式", example = "INVITE_ONLY")
    private Team.JoinMethod joinMethod;

    @Schema(description = "默认成员权限")
    private List<String> defaultPermissions;

    @Schema(description = "是否启用通知", example = "true")
    private Boolean enableNotifications;

    @Schema(description = "通知类型")
    private List<String> notificationTypes;

    @Schema(description = "是否要求两步验证", example = "false")
    private Boolean requireTwoFactor;

    @Schema(description = "会话超时时间(小时)", example = "24")
    private Integer sessionTimeout;

    @Schema(description = "是否允许成员邀请其他成员", example = "false")
    private Boolean allowMemberInvite;

    @Schema(description = "是否允许成员创建项目", example = "false")
    private Boolean allowMemberCreateProject;

    @Schema(description = "是否允许成员管理文件", example = "false")
    private Boolean allowMemberManageFiles;

    // 构造函数
    public TeamSettingsResponse() {}

    public TeamSettingsResponse(Long teamId, Team.Visibility visibility, Team.JoinMethod joinMethod) {
        this.teamId = teamId;
        this.visibility = visibility;
        this.joinMethod = joinMethod;
    }

    /**
     * 从Team实体创建响应DTO
     */
    public static TeamSettingsResponse from(Team team) {
        TeamSettingsResponse response = new TeamSettingsResponse();
        response.setTeamId(team.getId());
        response.setVisibility(team.getVisibility());
        response.setJoinMethod(team.getJoinMethod());
        response.setRequireTwoFactor(team.getRequireTwoFactor());
        response.setSessionTimeout(team.getSessionTimeout());

        // 解析JSON设置
        if (team.getTeamSettings() != null) {
            try {
                Map<String, Object> settings = objectMapper.readValue(
                    team.getTeamSettings(), 
                    new TypeReference<Map<String, Object>>() {}
                );

                response.setDefaultPermissions(getListFromSettings(settings, "defaultPermissions"));
                response.setEnableNotifications(getBooleanFromSettings(settings, "enableNotifications", true));
                response.setNotificationTypes(getListFromSettings(settings, "notificationTypes"));
                response.setAllowMemberInvite(getBooleanFromSettings(settings, "allowMemberInvite", false));
                response.setAllowMemberCreateProject(getBooleanFromSettings(settings, "allowMemberCreateProject", false));
                response.setAllowMemberManageFiles(getBooleanFromSettings(settings, "allowMemberManageFiles", false));

            } catch (JsonProcessingException e) {
                logger.error("解析团队设置JSON失败: teamId={}, error={}", team.getId(), e.getMessage());
                // 设置默认值
                response.setDefaultValues();
            }
        } else {
            response.setDefaultValues();
        }

        return response;
    }

    /**
     * 设置默认值
     */
    private void setDefaultValues() {
        this.defaultPermissions = List.of("VIEW_MEMBERS");
        this.enableNotifications = true;
        this.notificationTypes = List.of("MEMBER_JOIN", "MEMBER_LEAVE");
        this.allowMemberInvite = false;
        this.allowMemberCreateProject = false;
        this.allowMemberManageFiles = false;
    }

    /**
     * 从设置Map中获取List值
     */
    @SuppressWarnings("unchecked")
    private static List<String> getListFromSettings(Map<String, Object> settings, String key) {
        Object value = settings.get(key);
        if (value instanceof List) {
            return (List<String>) value;
        }
        return new ArrayList<>();
    }

    /**
     * 从设置Map中获取Boolean值
     */
    private static Boolean getBooleanFromSettings(Map<String, Object> settings, String key, Boolean defaultValue) {
        Object value = settings.get(key);
        if (value instanceof Boolean) {
            return (Boolean) value;
        }
        return defaultValue;
    }

    // Getter和Setter方法
    public Long getTeamId() {
        return teamId;
    }

    public void setTeamId(Long teamId) {
        this.teamId = teamId;
    }

    public Team.Visibility getVisibility() {
        return visibility;
    }

    public void setVisibility(Team.Visibility visibility) {
        this.visibility = visibility;
    }

    public Team.JoinMethod getJoinMethod() {
        return joinMethod;
    }

    public void setJoinMethod(Team.JoinMethod joinMethod) {
        this.joinMethod = joinMethod;
    }

    public List<String> getDefaultPermissions() {
        return defaultPermissions;
    }

    public void setDefaultPermissions(List<String> defaultPermissions) {
        this.defaultPermissions = defaultPermissions;
    }

    public Boolean getEnableNotifications() {
        return enableNotifications;
    }

    public void setEnableNotifications(Boolean enableNotifications) {
        this.enableNotifications = enableNotifications;
    }

    public List<String> getNotificationTypes() {
        return notificationTypes;
    }

    public void setNotificationTypes(List<String> notificationTypes) {
        this.notificationTypes = notificationTypes;
    }

    public Boolean getRequireTwoFactor() {
        return requireTwoFactor;
    }

    public void setRequireTwoFactor(Boolean requireTwoFactor) {
        this.requireTwoFactor = requireTwoFactor;
    }

    public Integer getSessionTimeout() {
        return sessionTimeout;
    }

    public void setSessionTimeout(Integer sessionTimeout) {
        this.sessionTimeout = sessionTimeout;
    }

    public Boolean getAllowMemberInvite() {
        return allowMemberInvite;
    }

    public void setAllowMemberInvite(Boolean allowMemberInvite) {
        this.allowMemberInvite = allowMemberInvite;
    }

    public Boolean getAllowMemberCreateProject() {
        return allowMemberCreateProject;
    }

    public void setAllowMemberCreateProject(Boolean allowMemberCreateProject) {
        this.allowMemberCreateProject = allowMemberCreateProject;
    }

    public Boolean getAllowMemberManageFiles() {
        return allowMemberManageFiles;
    }

    public void setAllowMemberManageFiles(Boolean allowMemberManageFiles) {
        this.allowMemberManageFiles = allowMemberManageFiles;
    }
}
